﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;



using System.Diagnostics;
using BierdopjeTV.Import;


namespace BierdopjeTV.Configuration
{
    public partial class Configuration : Form
    {

        private List<string> _Folders;
        //private List<Episodes> _Episodes;
        
        
        private List<Episodes> _Episodes;

        private Import.FileScanner FileScanner = new Import.FileScanner();

        public Configuration()
        {
            InitializeComponent();

            Tabbladen.SelectTab(1);
            UpdateSeriesTab();

            //Load all thingies.
            AlgemeneSettings();
            LoadImportPaths();
            dataGridImportPaden.AutoResizeColumns();
            LoadReplaceMents();


        }

        #region init_loading
        //Load Importpaths
        private void LoadImportPaths()
        {                    
            List<Database.Paths> _List = Database.Database.ImportPaths("Opvragen", 0, "");
            dataGridImportPaden.Rows.Clear();
            if (_List.Count > 0)
            {
                for (int i =0; i < _List.Count; i++)
                {
                    dataGridImportPaden.Rows.Add(_List[i].id.ToString(), true, _List[i].path);
                }
            }

            
        }

        //Load AlgemeneSettings
        private void AlgemeneSettings()
        {
            try { chkLocalFilesOnly.Checked = Convert.ToBoolean(Database.Database.getSettingValue("AlleenLokaleEpisodes")); }
            catch { }
            try { numPercentageViewed.Value = Convert.ToInt32(Database.Database.getSettingValue("EpisodeGezien")); }
            catch { }
            try { txtNLSub.Text = Database.Database.getSettingValue("AchtervoegselNLSub"); }
            catch { }
            try { txtENSub.Text = Database.Database.getSettingValue("AchtervoegselENSub"); }
            catch { }
            try { txtUserKey.Text = Database.Database.getSettingValue("APIKey"); }
            catch { }

        }

        //Load Replacements
        private void LoadReplaceMents()
        {

            dataGridReplaceMents.Rows.Clear();            

            List<Database.Replacemens> _List = Database.Database.ReplaceMents("Opvragen", 0, "", "");
             
            if (_List.Count > 0)
            {
                for (int i = 0; i < _List.Count; i++)
                {
                    dataGridReplaceMents.Rows.Add(_List[i].id.ToString(), false, _List[i].ShowNameOld, _List[i].ShowNameNew);
                }
            }

        }
        #endregion


        #region form_Events
        private void dataGridImportPaden_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            switch (e.ColumnIndex)
            {
                case 1:
                    try
                    {
                        //request id from that row.
                        int id = Convert.ToInt32(dataGridImportPaden.Rows[e.RowIndex].Cells[0].Value);
                        string path = dataGridImportPaden.Rows[e.RowIndex].Cells[2].Value.ToString();
                        if (id > 0) //if id is found, ask user to delelte
                        {
                            DialogResult Dialoog = MessageBox.Show("Weet je zeker dat je " + path + " wilt verwijderen", "vraagje:", MessageBoxButtons.YesNo);
                            if (Dialoog == DialogResult.Yes)
                            {
                                Database.Database.ImportPaths("Verwijderen", id, "");

                            }
                        }
                        LoadImportPaths();
                    }
                    catch { }
                 
                    break;
                
                case 2:
                    DialogResult result = folderBrowserDialog1.ShowDialog();
                    
                    if (result == DialogResult.OK)
                    {
                        int id = Convert.ToInt32(dataGridImportPaden.Rows[e.RowIndex].Cells[0].Value);
                        if (id > 0)
                        {                            
                            Database.Database.ImportPaths("Bijwerken", id, folderBrowserDialog1.SelectedPath);
                        }
                        else
                        {
                            Database.Database.ImportPaths("Toevoegen", 0, folderBrowserDialog1.SelectedPath);
                        }
                        LoadImportPaths();
                    }
                    break;
                
            }
                
        }

        private void Configuration_Load(object sender, EventArgs e)
        {

        }

        private void dataGridReplaceMents_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            
            
            if (dataGridReplaceMents.Rows[e.RowIndex].Cells[0].Value == null)
            {
                try
                {
                    string oud = dataGridReplaceMents.Rows[e.RowIndex].Cells[2].Value.ToString();
                    string nieuw = dataGridReplaceMents.Rows[e.RowIndex].Cells[3].Value.ToString();
                    if (oud != null && nieuw != null)
                    {
                        Database.Database.ReplaceMents("Toevoegen", 0, oud, nieuw);
                        LoadReplaceMents();
                    }
                  
                    
                }
                catch { }
                
                
            }
            else
            {
                int id = Convert.ToInt32(dataGridReplaceMents.Rows[e.RowIndex].Cells[0].Value);
                string oud = dataGridReplaceMents.Rows[e.RowIndex].Cells[2].Value.ToString();
                string nieuw = dataGridReplaceMents.Rows[e.RowIndex].Cells[3].Value.ToString();

                Database.Database.ReplaceMents("Bijwerken", id, oud, nieuw);               
                
            }                      

        }

        private void dataGridReplaceMents_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                int id = Convert.ToInt32(dataGridReplaceMents.Rows[e.RowIndex].Cells[0].Value);                
                
                if (id > 0) //if id is found, ask user to delelte
                {
                    DialogResult Dialoog = MessageBox.Show("Weet je zeker dat je deze wilt verwijderen", "vraagje:", MessageBoxButtons.YesNo);
                    if (Dialoog == DialogResult.Yes)
                    {
                        Database.Database.ReplaceMents("Verwijderen", id, "", "");
                       
                    }
                }
                
            }
            LoadReplaceMents();
        }

        private void chkLocalFilesOnly_CheckedChanged(object sender, EventArgs e)
        {
            Database.Database.UpdateSetting("AlleenLokaleEpisodes", chkLocalFilesOnly.Checked.ToString());
        }

        private void numPercentageViewed_ValueChanged(object sender, EventArgs e)
        {
            Database.Database.UpdateSetting("EpisodeGezien", numPercentageViewed.Value.ToString());
        }

        private void txtNLSub_TextChanged(object sender, EventArgs e)
        {
            Database.Database.UpdateSetting("AchtervoegselNLSub", txtNLSub.Text);
        }

        private void txtENSub_TextChanged(object sender, EventArgs e)
        {
            Database.Database.UpdateSetting("AchtervoegselENSub", txtENSub.Text);
        }
        #endregion


        #region backgroundworker
        private void backgroundScanner_DoWork(object sender, DoWorkEventArgs e)
        {
            //backgroundScanner.CancelAsync();
            //for (int i = 0; i < _Folders.Count; i++)
            //{
                
            //    _Episodes = FileScanner.getLocalShows(_Folders[i].ToString());
                
            //    backgroundScanner.ReportProgress(i);
            //    //Geef hem ff tijd!
            //    System.Threading.Thread.Sleep(500);
                
            //    //e.Cancel = true;
            //}
        }

        private void backgroundScanner_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {            
            progressBar1.Value = e.ProgressPercentage;         
            
            try
            {
                
                //txtLog.AppendText("Scanning " + _Folders[e.ProgressPercentage].ToString() + Environment.NewLine);
                //for (int i = 0; i < _Episodes.Count; i++)
                //{
                //    dataGridView1.Rows.Add(_Episodes[i].Path, _Episodes[i].ShowName, _Episodes[i].Season, _Episodes[i].Episode, _Episodes[i].Source, _Episodes[i].Codec);
                //    txtLog.AppendText("\t" + _Episodes[i].Path + Environment.NewLine);
                //}
            }
            catch { }
        }

        private void backgroundScanner_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }
        #endregion

        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////


        private void btnImport_Click(object sender, EventArgs e)
        {
         
            dataGridView1.Rows.Clear();
            txtLog.Clear();

            //backgroundWorker1.ReportProgress(0, file);
            _Folders =  Database.Database.GetImportPaths();
            if (_Folders.Count > 0)
            {
                progressBar1.Maximum = _Folders.Count - 1;
            }
            else
            {
                txtLog.AppendText("Niets te doen");
            }
            
            
            API.APIFunctions _ApiShow = new API.APIFunctions();

            //List<BierdopjeTV.API.BierdopjeShows> ApiShow = _ApiShow.FindShowByName(ShowName);


            for (int i = 0; i < _Folders.Count; i++)
            {
                progressBar1.Value = i;
                _Episodes = FileScanner.getLocalShows(_Folders[i].ToString());

                txtLog.AppendText("Scanning " + _Folders[i].ToString() + Environment.NewLine);
                for (int j = 0; j < _Episodes.Count; j++)
                {
                    Application.DoEvents();
                    //this.Refresh();
                    if (_Episodes[j].ShowName != null)
                    {
                    //     MessageBox.Show(BierdopjeTV.API.BierdopjeShows.getShowID(_Episodes[j].ShowName).ToString());

                    }
                    dataGridView1.Rows.Add(_Episodes[j].Path, _Episodes[j].ShowName, _Episodes[j].Season, _Episodes[j].Episode, _Episodes[j].Source, _Episodes[j].Codec);
                    txtLog.AppendText("\t" + _Episodes[j].Path + Environment.NewLine);
                }

                //e.Cancel = true;
            }
            txtLog.AppendText("Bezig met opzoeken van data vanaf bierdopje.com...");
            //Update BierdopjeEpisodes!
            API.BierdopjeEpisodes.WhichShowsNeedUpdate();
            txtLog.AppendText("KLAAR!");

        }

        private void txtUserKey_TextChanged(object sender, EventArgs e)
        {
            Database.Database.UpdateSetting("UserKey", txtUserKey.Text);
        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }
        //treeSeries

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            Debug.Print(treeSeries.SelectedNode.Text);
        }

        private void Tabbladen_SelectedIndexChanged(object sender, EventArgs e)
        {
            //als series tabblad geselecteerd wordt
            if (Tabbladen.SelectedIndex == 2)
            {
                UpdateSeriesTab();
            }
        }


        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////

        private void UpdateSeriesTab()
        {
            Debug.Print("UPDATE!");

            treeSeries.Nodes.Clear();

            List<Database.GUISeries> _Shows;
            List<Database.GUISeasons> _Seasons;
            List<Database.GUIEpisodes> _Episodes;
            int ShowID, Season;
            string episodeFormat = "";
            _Shows = Database.DBShows.getShows();
            

            for (int i = 0; i < _Shows.Count; i++)
            {
                //Add Shows nodes
                ShowID = _Shows[i].ShowID;
                treeSeries.Nodes.Add(ShowID.ToString(), _Shows[i].ShowName.ToString());
                if (_Shows[i].Downloaded < 1)
                {
                    treeSeries.Nodes[i].ForeColor = Color.OrangeRed;
                }
                _Seasons = Database.DBSeasons.getSeasons(ShowID);

                for (int j = 0; j < _Seasons.Count; j++)
                {
                    //Add seasons
                    Season = _Seasons[j].Season;
                    treeSeries.Nodes[ShowID.ToString()].Nodes.Add(Season.ToString(), "Season " + Season.ToString());
                    if (_Seasons[j].Downloaded == _Seasons[j].Watched)
                    {
                        treeSeries.Nodes[ShowID.ToString()].Nodes[j].ForeColor = Color.Blue;
                    }
                    if (_Seasons[j].Downloaded < 1)
                    {
                        treeSeries.Nodes[ShowID.ToString()].Nodes[j].ForeColor = Color.OrangeRed;
                    }
                    _Episodes = Database.DBEpisodes.getEpisodes(Convert.ToInt32(ShowID), Convert.ToInt32(Season));
                    for (int k = 0; k < _Episodes.Count; k++)
                    {
                        //add episodes
                        episodeFormat = _Episodes[k].Season.ToString() + "x" + _Episodes[k].Episode.ToString() + " " + _Episodes[k].Titel;
                        treeSeries.Nodes[ShowID.ToString()].Nodes[Season.ToString()].Nodes.Add(_Episodes[k].EpisodeID.ToString(), episodeFormat);
                        if (_Episodes[k].Wachted == 1)
                        {
                            treeSeries.Nodes[ShowID.ToString()].Nodes[Season.ToString()].Nodes[k].ForeColor = Color.Blue;
                        } 
                        if (_Episodes[k].FileName.Length < 1)
                        {
                               treeSeries.Nodes[ShowID.ToString()].Nodes[Season.ToString()].Nodes[k].ForeColor = Color.OrangeRed;
                        }


                    }

                }
                _Seasons = null;
            }

  

            //treeSeries.Nodes["444"].Nodes.Add("SubNode 444");

         
        }

        private void treeSeries_AfterSelect(object sender, TreeViewEventArgs e)
        {
       
        }

        private void showEpisodeDetails(string episodeID)
        {
            ShowDetails.Rows.Clear();
            ShowDetails.ColumnCount = 2;
            ShowDetails.ColumnHeadersVisible = false;
            
            SQLite.NET.SQLiteResultSet _REsults;

            string _Query = "";
            _Query += "SELECT" + Environment.NewLine;
            _Query += "	BierdopjeShows.ShowName," + Environment.NewLine;
            _Query += "	BierdopjeShows.ShowID,	" + Environment.NewLine;
            _Query += "	BierdopjeEpisodes.EpisodeID," + Environment.NewLine;
            _Query += "	BierdopjeEpisodes.Season," + Environment.NewLine;
            _Query += "	BierdopjeEpisodes.Episode," + Environment.NewLine;
            _Query += "	BierdopjeEpisodes.Titel," + Environment.NewLine;
            _Query += "	BierdopjeEpisodes.AirDate," + Environment.NewLine;
            _Query += "	Episodes.Path," + Environment.NewLine;
            _Query += "	BierdopjeEpisodes.Watched," + Environment.NewLine;
            _Query += "	BierdopjeEpisodes.Downloaded," + Environment.NewLine;
            _Query += "	BierdopjeEpisodes.SubNLDownloaded AS SubsNL," + Environment.NewLine;
            _Query += "	BierdopjeEpisodes.SubENDownloaded AS SubsEN," + Environment.NewLine;
            _Query += "	Episodes.Source," + Environment.NewLine;
            _Query += "	Episodes.Codec," + Environment.NewLine;
            _Query += "	BierdopjeEpisodes.Summary" + Environment.NewLine;            
            _Query += "" + Environment.NewLine;
            _Query += "	" + Environment.NewLine;
            _Query += "FROM" + Environment.NewLine;
            _Query += "	BierdopjeEpisodes" + Environment.NewLine;
            _Query += "LEFT JOIN" + Environment.NewLine;
            _Query += "	Episodes ON" + Environment.NewLine;
            _Query += "	(" + Environment.NewLine;
            _Query += "		Episodes.ShowID = BierdopjeEpisodes.ShowID" + Environment.NewLine;
            _Query += "		AND" + Environment.NewLine;
            _Query += "		Episodes.Season = BierdopjeEpisodes.Season" + Environment.NewLine;
            _Query += "		AND" + Environment.NewLine;
            _Query += "		Episodes.Episode = BierdopjeEpisodes.Episode" + Environment.NewLine;
            _Query += "	)" + Environment.NewLine;
            _Query += "LEFT JOIN" + Environment.NewLine;
            _Query += "	BierdopjeShows ON BierdopjeShows.ShowID = BierdopjeEpisodes.ShowID" + Environment.NewLine;
            _Query += "WHERE" + Environment.NewLine;
            _Query += "	BierdopjeEpisodes.EpisodeID = " + episodeID + Environment.NewLine;

            _REsults = Helpers.SqliteHelper.ExecuteQuery(_Query);

            if (_REsults.Rows.Count > 0)
            {

                for (int i = 0; i < _REsults.ColumnNames.Count; i++)
                {
                    ShowDetails.Rows.Add(_REsults.ColumnNames[i], _REsults.Rows[0].fields[i]);
                }
                Debug.Print(_REsults.Rows.Count.ToString());
            }

            
        }

        private void treeSeries_AfterSelect_1(object sender, TreeViewEventArgs e)
        {
            int i = 0;
            i = treeSeries.SelectedNode.Index;

            Debug.Print("level: " + e.Node.Level.ToString());
            if (e.Node.Level == 2)
            {
                Debug.Print(e.Node.Name);
                showEpisodeDetails(e.Node.Name);
            }
        }
            

    }
}

